<?php defined('SYSPATH') or die('No direct script access.');
	
	class Controller_Support extends Controller{
		
		public function action_backup(){
			
			$nombre_backup = "diastole-".date("Y-m-d").".sql";
 						
			$f=fopen($nombre_backup,"w");
			fwrite($f,"# Diastole Database Dump ".date("Y-m-d")."\r\n");
						
			// RECUPERO LAS TABLAS
			$tables_list = DB::query(Database::SELECT,"SHOW TABLES FROM diastole")->execute()->current();
			
			// RECORRO TODAS LAS TABLAS
			foreach($tables_list as $table){
				
				$sqlContent = "";
				
				//Recupero Estructura e informacion de creacion
				$createQuery = DB::query(Database::SELECT,"SHOW CREATE TABLE $table")->execute()->current();
								
				$sqlContent.= "# Estructura Tabla : $table \r\n";
				$sqlContent.= $createQuery["Create Table"]."\r\n\r\n";
				
				//Volcado de Registros de Tabla
				$sqlContent.= "# Datos Tabla : $table \r\n";
				
				//Recuperacion de campos 
				$fieldsQuery = DB::query(Database::SELECT,"SHOW COLUMNS FROM $table")->execute();
				$num_fields = $fieldsQuery->count();
				$fieldList = $fieldsQuery->as_array();
				
				$sqlFields = array();
				foreach($fieldList as $field){
					$sqlFields[]=$field["Field"];
				}
				
				$sqlContent.= "INSERT INTO $table (".implode(",",$sqlFields).") VALUES\r\n";
				
				$recordsStr = array();
				$recordsQuery = DB::Select()->from("$table")->execute()->as_array();
				foreach($recordsQuery as $record){
					$data = array();
					foreach($record as $key=>$value){
						$data[] = "'".$value."'";
					}
					$recordsStr[] = "(".implode(", ",$data).")";
				}
				$sqlContent.= "(".implode(", ",$recordsStr).");\r\n\r\n";
				
				fwrite($f,$sqlContent);
			}
					
			fclose($f);
			
			// CABECERAS PARA DESCARGAR EL ARCHIVO
			header ("Content-Disposition: attachment; filename=".$nombre_backup); 
			header ("Content-Type: application/octet-stream"); 
			header ("Content-Length: ".filesize($nombre_backup)); 
			readfile($nombre_backup);
			

			
			
			
		}
		
		public function action_restore(){
			//dummy method
		}
		
	}
?>